﻿using NetworkLib;
using PBO.Util;
using PokemonBattle.BattleRoom.Client;
using PokemonBattle.RoomList.Client;
using PokemonBattle.RoomListClient;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace PBO.Forms.NetworkForm
{
    public partial class RoomListForm : Form
    {
        public RoomListForm()
        {
            InitializeComponent();
        }

        private RoomListClient _client;
        private User _userInfo;

        public RoomListForm(User user)
        {
            InitializeComponent();

            Icon = Properties.Resources.PokemonBall;
            RoomList.ListViewItemSorter = new ListSorter(1);
            _userInfo = user;
            Connect();
        }

        private void Connect()
        {
            _client = new RoomListClient(Properties.Settings.Default.ServerAddress);
            _client.OnUserAddRooms += UpdateList;
            _client.OnDisconnected += OnDisconnected;
            _client.OnConnectFail += OnConnectFail;
            _client.OnAddRoomInfo += AddRoom;
            _client.OnUpdateRoomInfo += UpdateRoom;
            _client.OnRemoveRoomInfo += RemoveRoom;

            _client.Initialize();
            _client.RunThread();
        }

        private void UpdateList(List<Room> rooms)
        {

            if (!InvokeRequired)
            {
                RoomList.BeginUpdate();
                RoomList.Items.Clear();

                for (int i = 0; i < rooms.Count; i++)
                {
                    Room roomInfo = rooms[i];
                    ListViewItem item = new ListViewItem(new string[3] {
                        roomInfo.Name,
                        roomInfo.UserCount.ToString(),
                        roomInfo.MaxUser.ToString()
                    });
                    item.Name = roomInfo.Identity.ToString();
                    RoomList.Items.Add(item);
                }
                RoomList.EndUpdate();
            }
            else
            {
                Invoke(new RoomListDelegate(UpdateList), rooms);
            }
        }

        private void AddRoom(Room info)
        {
            if (!InvokeRequired)
            {
                ListViewItem item = new ListViewItem(new string[3] {
                    info.Name,
                    info.UserCount.ToString(),
                    info.MaxUser.ToString()
                });
                item.Name = info.Identity.ToString();
                RoomList.Items.Add(item);
            }
            else
            {
                Invoke(new RoomDelegate(AddRoom), info);
            }
        }

        private void UpdateRoom(Room info)
        {
            if (!InvokeRequired)
            {
                ListViewItem[] item = RoomList.Items.Find(info.Identity.ToString(), false);
                if (item.Length > 0)
                {
                    item[0].SubItems[0].Text = info.Name;
                    item[0].SubItems[1].Text = info.UserCount.ToString();
                    item[0].SubItems[2].Text = info.MaxUser.ToString();
                }
            }
            else
            {
                Invoke(new RoomDelegate(UpdateRoom), info);
            }
        }

        private void RemoveRoom(int identity)
        {
            if (!InvokeRequired)
            {
                RoomList.Items.RemoveByKey(identity.ToString());
            }
            else
            {
                Invoke(new RemoveRoomDelegate(RemoveRoom), identity);
            }
        }

        private void OnConnectFail(NetworkException exception)
        {
            ModShare.ShowInformation(this, "无法连接到服务器", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            ShowAdvancedOption();
        }

        private void OnDisconnected()
        {
            ModShare.ShowInformation(this, "与服务器断开了连接", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            ShowAdvancedOption();
        }

        private string _address;
        private string _roomName;

        private void ShowAdvancedOption()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(ShowAdvancedOption));
            }
            else
            {
                AdvanceLinkForm advanceForm = new AdvanceLinkForm(_userInfo);
                advanceForm.MdiParent = this.MdiParent;
                advanceForm.Show();
                Close();
            }
        }

        private void Disconnect()
        {
            if (_client != null)
            {
                _client.Stop();
                _client = null;
            }
        }

        #region event

        private void RoomList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (RoomList.SelectedItems.Count > 0)
            {
                Room info = _client.GetRoom(Convert.ToInt32(RoomList.SelectedItems[0].Name));
                InfoText.Text = info.Description;
                EnterButton.Enabled = true;
            }
            else
            {
                EnterButton.Enabled = false;
                InfoText.Clear();
            }
        }

        private void RoomList_DoubleClick(object sender, EventArgs e)
        {
            EnterButton.PerformClick();
        }

        private void RoomListForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Disconnect();
        }

        #endregion

        #region Button

        private void EnterButton_Click(object sender, EventArgs e)
        {
            if (RoomList.SelectedIndices.Count == 0)
                return;
            Room info = _client.GetRoom(Convert.ToInt32(RoomList.SelectedItems[0].Name));
            ((MainForm)MdiParent).BuildRoomUserForm(_userInfo, info.Address, info.Name).Show();
            Close();
        }

        private void AdvanceButton_Click(object sender, EventArgs e)
        {
            ShowAdvancedOption();
        }

        private void Cancel_Button_Click(object sender, EventArgs e)
        {
            Close();
        }

        #endregion

    }
}
